<template>
  <a-modal
    :centered="true"
    :title="title"
    :bodyStyle="{height: modalHeight()}"
    :visible="visible"
    :width="modalWidth()"
    @cancel="handleCancel"
    @ok="handleSubmit"
    okText="确定"
    cancelText="取消"
    class="update-modal">
    <div :style="modalStyle()">
      <a-spin :spinning="confirmLoading">
        <a-form :form="form">
          <a-form-item
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            has-feedback
            label="概念A">
            <div @click="conceptAClick">
              <a-select
                :open="conceptAVisible"
                placeholder="请选择概念A"
                v-decorator="['conceptAId', {rules: [{required: true, message: '请选择概念A!'}]}]"
                @change="(v)=>conceptAChange(v)">
                <a-select-option
                  v-for="(it) in conceptAList"
                  :key="'a_'+it.id"
                  :value="it.id">
                  {{ it.name }}
                </a-select-option>
              </a-select>
            </div>
          </a-form-item>
          <a-form-item
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            has-feedback
            label="概念B">
            <div @click="conceptBClick">
              <a-select
                placeholder="请选择概念B"
                :open="conceptBVisible"
                v-decorator="['conceptBId', {rules: [{required: true, message: '请选择概念B!'}]}]"
                @change="(v)=>conceptBChange(v)">
                <a-select-option
                  v-for="(it) in conceptBList"
                  :key="'b_'+it.id"
                  :value="it.id">
                  {{ it.name }}
                </a-select-option>
              </a-select>
            </div>
          </a-form-item>
          <a-form-item
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            has-feedback
            label="关系名称">
            <a-select
              @change="(v)=>onRelationChange(v)"
              placeholder="请选择关系"
              v-decorator="['relationId', {rules: [{required: true, message: '请选择关系!'}]}]">
              <a-select-option
                v-for="(it) in relationList"
                :key="it.id"
                :value="it.id">
                {{ it.chName }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            has-feedback
            label="执行器">
            <a-select
              placeholder="请选择执行器"
              v-decorator="['executorId', {rules: [{required: true, message: '请选择执行器!'}]}]">
              <a-select-option
                v-for="(it) in actuatorList"
                :key="it.id"
                :value="it.id">
                {{ it.title }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            has-feedback
            label="执行任务Cron">
            <a-input
              v-decorator="['cron', {rules: [{required: true, message: '请输入执行任务!'}]}]"
              placeholder="请输入执行任务" />
          </a-form-item>
          <a-divider>增量设置</a-divider>
          <div style="width: 100%;display: inline-flex;justify-content: space-around">
            <span
              v-for="item in ['内容','增量类型','操作']"
              :key="item"
              style="font-weight: bold;margin-bottom: 6px">
              {{ item }}
            </span>
          </div>
          <a-row
            :gutter="24"
            style="margin-top: 6px"
            :key="item.uuid"
            v-for="(item ,index) in increments">
            <a-col :span="8">
              <a-input :disabled="true" :value="item.name"></a-input>
            </a-col>
            <a-col :span="8">
              <a-input :disabled="true" :value="item.incrementType"></a-input>
            </a-col>
            <a-col :span="8" style="text-align: center">
              <div style="display: inline-block ;padding: 0;margin-top: 6px">
                <span @click="editIncrement(index)">编辑</span>
                <a-divider type="vertical"></a-divider>
                <span @click="deleteIncrement(index,item.conceptId)">删除</span>
              </div>
            </a-col>
          </a-row>
          <icon-font
            v-if="showAppend"
            @click="pushIncrement"
            style="font-size: 30px;margin-bottom: 16px;margin-top:12px;color: #1890ff;margin-left: 12px"
            type="icon-roundadd" />
          <a-divider>分片设置</a-divider>
          <a-row :gutter="24">
            <a-col :span="12">
              <a-form-item
                :labelCol="centerLabelCol"
                :wrapperCol="centerWrapperCol"
                has-feedback
                label="概念A分片字段"
              >
                <a-select
                  placeholder="请选择概念A分片字段"
                  v-decorator="['conceptAShardCol', {rules: [{required: true, message: '请选择概念A分片字段!'}]}]">
                  <a-select-option
                    v-for="(it) in conceptAColumnList"
                    :key="it.id"
                    :value="it.columnName">
                    {{ it.columnName }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item
                :labelCol="centerLabelCol"
                :wrapperCol="centerWrapperCol"
                has-feedback
                label="概念B分片字段">
                <a-select
                  placeholder="请选择概念B分片字段"
                  v-decorator="['conceptBShardCol', {rules: [{required: true, message: '请选择概念B分片字段!'}]}]">
                  <a-select-option
                    v-for="(it) in conceptBColumnList"
                    :key="it.id"
                    :value="it.columnName">
                    {{ it.columnName }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="24">
            <a-col :span="12">
              <a-form-item
                :labelCol="centerLabelCol"
                :wrapperCol="centerWrapperCol"
                has-feedback
                style="white-space: pre-wrap;"
                label="建立关系是否需要分片">
                <a-select
                  placeholder="请选择建立关系是否需要分片"
                  v-decorator="['isShardColRelation',{initialValue:0},{rules: [{required: false, message: '请选择建立关系是否需要分片!'}]}]">
                  <a-select-option
                    v-for="(it) in [{'name':'否','value':0},{'name':'是','value':1}]"
                    :key="it.value"
                    :value="it.value">
                    {{ it.name }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item
                :labelCol="centerLabelCol"
                :wrapperCol="centerWrapperCol"
                has-feedback
                label="分片关系字段">
                <a-select
                  placeholder="请选择分片关系字段"
                  v-decorator="['relationShardCol', {rules: [{required: false, message: '请选择分片关系字段!'}]}]">
                  <a-select-option
                    v-for="(it) in shardRelationship"
                    :key="it.id"
                    :value="it.id">
                    {{ it.conceptName }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </a-spin>
    </div>
  </a-modal>
</template>

<script>
import { register } from '@/utils/drag_modal'
import { schemaColumnPage, schemaList } from '@/api/modular/main/knowl/schema/schemaManage'
import { jobExecutorManagementList } from '@/api/modular/main/knowl/executor/executorManagement'
import { listByConcept, listRelationOrSchema } from '@/api/modular/main/knowl/relation/relationManage'
import { addGraphPublish, publishEntityDetail } from '@/api/modular/main/knowl/data_fusion/publishManager'

export default {
  data() {
    return {
      conceptAId: undefined,
      conceptBId: undefined,
      relationId: undefined,
      showAppend: true,
      conceptAVisible: false,
      conceptBVisible: false,
      editIncrementIndex: -1,
      conceptAList: [],
      conceptBList: [],
      conceptAColumnList: [],
      conceptBColumnList: [],
      actuatorList: [],
      relationList: [],
      increments: [],
      shardRelationship: [],
      labelCol: {
        xs: { span: 24 },
        sm: { span: 3 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 21 }
      },
      centerLabelCol: {
        xs: { span: 24 },
        sm: { span: 9 }
      },
      centerWrapperCol: {
        xs: { span: 24 },
        sm: { span: 15 }
      },
      visible: false,
      title: '',
      id: undefined,
      confirmLoading: false,
      form: this.$form.createForm(this)
    }
  },
  watch: {
    increments: {
      handler(newValue, old) {
        this.showAppend = newValue.length !== 3
      }
    }
  },
  methods: {
    loadSchemaList() {
      this.confirmLoading = true
      schemaList({}).then((res) => {
        console.log(res)
      }).catch((e) => {
        console.log(e)
      }).finally(() => {
        this.confirmLoading = false
      })
    },
    conceptAClick() {
      if (!this.conceptAVisible) {
        this.confirmLoading = true
        listRelationOrSchema(true, this.conceptBId)
          .then((res) => {
            if (res.code === 200) {
              this.conceptAVisible = !this.conceptAVisible
              this.conceptAList = res.data
            } else {
              this.$message.error(res.message)
            }
          }).catch((e) => {
          console.log(e)
        }).finally(() => {
          this.confirmLoading = false
        })
      } else {
        this.conceptAVisible = false
      }
    },
    conceptBClick() {
      if (!this.conceptBVisible) {
        this.confirmLoading = true
        listRelationOrSchema(false, this.conceptAId)
          .then((res) => {
            if (res.code === 200) {
              this.conceptBVisible = !this.conceptBVisible
              this.conceptBList = res.data
            } else {
              this.$message.error(res.message)
            }
          }).catch((e) => {
          console.log(e)
        }).finally(() => {
          this.confirmLoading = false
        })
      } else {
        this.conceptBVisible = false
      }
    },
    conceptAChange(id) {
      this.conceptAVisible = false
      this.increments = []
      this.conceptAId = id
      this.conceptAColumnList = []
      this.loadSchemaAColumnsList(id)
      this.form.setFieldsValue({
        'conceptAShardCol': undefined,
        'relationId': undefined
      })
      this.listByConceptList()
    },
    conceptBChange(id) {
      this.increments = []
      this.conceptBId = id
      this.conceptBVisible = false
      const item = this.conceptBList.find((it) => it.id === id)
      this.conceptB = item['name']
      this.conceptBColumnList = []
      this.loadSchemaBColumnsList(id)
      this.form.setFieldsValue({
        'conceptBShardCol': undefined,
        'relationId': undefined
      })
      this.listByConceptList()
    },
    listByConceptList() {
      const schemaFrom = this.conceptAId
      const schemaTo = this.conceptBId
      if (schemaFrom && schemaTo) {
        listByConcept({
          'schemaFrom': schemaFrom,
          'schemaTo': schemaTo
        })
          .then((res) => {
            if (res.code === 200) {
              this.relationList = res.data
            }
          }).catch((e) => {
          console.log(e)
        })
      }
    },
    onRelationChange(id) {
      this.increments = []
      this.relationId = id
      const item = this.relationList.find((it) => it.id === id)
      this.relationName = item['chName']
    },
    modalStyle() {
      return {
        'overflow-y': 'overlay',
        'overflow-x': 'hidden',
        'height': '100%',
        'max-height': '100%',
        'padding-right': '9px'
      }
    },
    modalHeight() {
      return (document.body.clientHeight * 0.8) + 'px'
    },
    modalWidth() {
      return document.body.clientWidth * 0.5
    },
    // 初始化方法
    add() {
      this.id = undefined
      this.title = '添加发布信息'
      this.visible = true
      register(true)
      this.loadActuator()
    },
    // 编辑
    edit(item) {
      this.id = item.id
      this.title = '编辑发布信息'
      this.visible = true
      register(true)
      this.confirmLoading = true
      publishEntityDetail({
        'schemaFrom': true,
        'id': undefined
      }, {
        'schemaFrom': false,
        'id': undefined
      }, {
        'schemaFrom': item.conceptAId,
        'schemaTo': item.conceptBId
      }, item.id)
        .then((res) => {
          this.conceptAList = res[0]
          this.conceptBList = res[1]
          this.relationList = res[2]
          this.actuatorList = res[3]
          this.conceptAId = item.conceptAId
          this.conceptBId = item.conceptBId
          this.relationId = item.relationId
          const content = res[4]
          this.form.setFieldsValue({
            conceptAId: item.conceptAId,
            conceptBId: item.conceptBId,
            relationId: item.relationId,
            executorId: parseInt(item.executorId),
            cron: content.cron,
            isShardColRelation: content.isShardColRelation ?? 0
          })
          if (content.increments) {
            const temp = JSON.parse(content.increments)
            const assembleArray = this.getAssembleArray()
            const newIncrements = []
            temp.forEach((it) => {
              const entity = assembleArray.find((i) => i.id === it['incrementObj'])
              newIncrements.push({
                'id': it.incrementObj,
                'incrementObj': it.incrementObj,
                'name': entity ? (entity.name || entity.chName) : undefined,
                'incrementType': it['incrementType'],
                'incrementTimePattern': it['incrementTimePattern'],
                'timeIncrementCol': it['timeIncrementCol'],
                'idIncrementCol': it['idIncrementCol'],
                'incrementStartId': it['incrementStartId'],
                'incrementStartTime': it['incrementStartTime']
              })
            })
            this.increments = newIncrements
          }
        }).catch((e) => {
        console.log(e)
      }).finally(() => {
        this.confirmLoading = false
      })
      this.loadSchemaAColumnsList(item.conceptAId, item.conceptAShardCol)
      this.loadSchemaBColumnsList(item.conceptBId, item.conceptBShardCol)
    },

    setIncrementValue(value) {
      if (this.exist(this.increments, value['incrementObj'])) {
        let item = this.increments[this.editIncrementIndex]
        item = Object.assign(item, value)
        item['id'] = value['incrementObj']
        this.increments.splice(this.editIncrementIndex, 1, item)
      } else {
        const item = Object.assign({}, value)
        item['id'] = value['incrementObj']
        this.increments.push(item)
      }
    },
    exist(list, id) {
      return list.find((i) => i.id === id)
    },
    getAssembleArray() {
      const assembleArray = []
      assembleArray.push.apply(assembleArray, this.conceptAList)
      assembleArray.push.apply(assembleArray, this.conceptBList)
      assembleArray.push.apply(assembleArray, this.relationList)
      return assembleArray
    },
    pushIncrement() {
      if (!this.conceptAId && !this.conceptBId && !this.relationId) {
        this.$message.error('请选择概念或者关系')
        return
      }
      const objs = []
      const ids = [this.conceptAId, this.conceptBId, this.relationId]
      const assembleArray = this.getAssembleArray()
      ids.forEach((it) => {
        const cache = this.increments.find((i) => i.id === it)
        if (!cache) {
          const entity = assembleArray.find((i) => i.id === it)
          if (entity) {
            objs.push({
              id: it,
              name: entity.name || entity.chName
            })
          }
        }
      })
      this.editIncrementIndex = this.increments.length
      this.$emit('setIncrement', {
        'incrementType': '无',
        'list': objs,
        'edit': false
      })
    },
    editIncrement(index) {
      const item = this.increments[index]
      this.editIncrementIndex = index
      const objs = []
      if (this.conceptAId && this.exist(this.increments, this.conceptAId)) {
        objs.push({
          'id': this.conceptAId,
          'name': this.conceptAList.find((it) => it.id === this.conceptAId).name
        })
      }
      if (this.conceptBId && this.exist(this.increments, this.conceptBId)) {
        objs.push({
          'id': this.conceptBId,
          'name': this.conceptBList.find((it) => it.id === this.conceptBId).name
        })
      }
      if (this.relationId && this.exist(this.increments, this.relationId)) {
        objs.push({
          'id': this.relationId,
          'name': this.relationList.find((it) => it.id === this.relationId).chName
        })
      }
      this.$emit('setIncrement', {
        'incrementType': item['incrementType'],
        'incrementTimePattern': item['incrementTimePattern'],
        'timeIncrementCol': item['timeIncrementCol'],
        'idIncrementCol': item['idIncrementCol'],
        'incrementStartId': item['incrementStartId'],
        'incrementStartTime': item['incrementStartTime'],
        'id': item['id'],
        'list': objs,
        'edit': true
      })
    },
    deleteIncrement(index, conceptId) {
      this.increments.splice(index, 1)
    },

    insertValue(value) {
      this.confirmLoading = true
      value['id'] = this.id
      this.increments.forEach((i) => {
        i['id'] = undefined
      })
      value['increments'] = JSON.stringify(this.increments)
      addGraphPublish(value)
        .then((res) => {
          if (res.code === 200) {
            this.$emit('ok')
            this.$message.success('操作成功!')
            this.handleCancel()
          } else {
            this.$message.error(res.msg)
          }
        }).catch((e) => {
        console.log(e)
      }).finally(() => {
        this.confirmLoading = false
      })
    },
    /**
     * 准备提交表单
     */
    handleSubmit() {
      const { form: { validateFields } } = this
      validateFields((errors, values) => {
        if (!errors) {
          for (const key in values) {
            if (typeof (values[key]) === 'object') {
              values[key] = JSON.stringify(values[key])
            }
          }
          this.insertValue(values)
        }
      })
    },
    handleCancel() {
      register(false)
      this.form.resetFields()
      this.conceptBId = undefined
      this.conceptAId = undefined
      this.relationId = undefined
      this.conceptAVisible = false
      this.conceptBVisible = false
      this.conceptAList = []
      this.increments = []
      this.conceptBList = []
      this.relationList = []
      this.visible = false
    },

    loadActuator() {
      jobExecutorManagementList({}).then((res) => {
        this.actuatorList = res.data
      }).catch((e) => {
        console.log(e)
      })
    },
    loadSchemaAColumnsList(conceptId, formField) {
      schemaColumnPage({
        'conceptId': conceptId
      }).then((res) => {
        if (res.code === 200) {
          this.conceptAColumnList = res.content
          if (formField) {
            this.form.setFieldsValue({
              conceptAShardCol: formField
            })
          }
        }
      }).catch((e) => {
        console.log(e)
      })
    },
    loadSchemaBColumnsList(conceptId, formField) {
      schemaColumnPage({
        'conceptId': conceptId
      }).then((res) => {
        if (res.code === 200) {
          this.conceptBColumnList = res.content
          if (formField) {
            this.form.setFieldsValue({
              conceptBShardCol: formField
            })
          }
        }
      }).catch((e) => {
        console.log(e)
      })
    }
  }
}
</script>

<style lang="less" scoped>
::-webkit-scrollbar {
  width: 0;
  background-color: rgba(240, 240, 240, 1);
}
</style>
